/**
 *HTTP工具类
 */
import axios, {AxiosRequestConfig} from 'axios'
import {useLayoutStore} from "@/common/store/modules/layout";
import {useUserStore} from "@/common/store/modules/user";
import {message as $message} from "ant-design-vue";
import {getToken} from "@/common/util/cache";

//需要校验重复提交的URL
const CHECK_REPEAT_URL = []

const $http = axios.create(<AxiosRequestConfig>{
    timeout: 100 * 1000
});

// 请求拦截
$http.interceptors.request.use(config => {
    const {url, method, baseURL} = config
    // config.headers['Access-Control-Allow-Origin'] = "*"

    /** 非全路径,拼接URL+Token **/
    let haveHttp = url.indexOf("http://").toString() !== "-1";
    let haveHttps = url.indexOf("https://").toString() !== "-1";
    if (!haveHttp && !haveHttps) {
        config.url = import.meta.env.VITE_SERVER_URL + url;
        config.headers['Token'] = getToken()
    }

    /** 检查重复提交 **/
    if (CHECK_REPEAT_URL.indexOf(url) != -1) {
        //console.log("【URL重复提交检查】" + url)
        let reqObj = {
            KEY: "req_key_" + config.url,
            url: config.url,
            data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
            time: new Date().getTime()
        }
        let sessionRequestStr = sessionStorage.getItem(reqObj.KEY)
        //首次提交(无需处理)
        if (sessionRequestStr === undefined || sessionRequestStr === null || sessionRequestStr === '') {
            sessionStorage.setItem(reqObj.KEY, JSON.stringify(reqObj))
        }
        //检查重复提交（ 请求地址、请求数据、间隔时间(ms)，小于此时间视为重复提交）
        else {
            let sessionRequestObj = JSON.parse(sessionRequestStr)
            const {url, data, time} = sessionRequestObj;
            const interval = 1000;
            if (url === reqObj.url && data === reqObj.data && reqObj.time - time < interval) {
                const message = '数据正在处理';
                //console.log("sessionRequestObj", sessionRequestObj)
                //console.log("reqObj", reqObj)
                $message.warning(message).then(r => {
                })
                return Promise.reject(new Error(message))
            } else {
                sessionStorage.setItem(reqObj.KEY, JSON.stringify(reqObj))
            }
        }
    }

    return config;
}, error => {
    return Promise.reject(error)
});

//响应拦截
$http.interceptors.response.use(async response => {
    // //console.log("【response】", response)

    // 二进制数据则直接返回
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
        return response.data
    }

    let code = response.data.code
    let message = response.data.message

    if (code == '200') {
        return response.data;
    }

    //登录失效
    if (code == '401') {
        // console.log(401)
        closeLoading()
        useUserStore().isLogOut = true;
        //http
        return response.data;
    }

    if (code == '500') {
        // console.log(500)
        closeLoading()
        $message.error(message, 3)
        return Promise.reject(new Error(message))
    }
}, error => {
    //异常情况关闭架加载框
    closeLoading()

    //服务端未开启，或者网络错误
    if (error.code == 'ERR_NETWORK') {
        $message.warning("请求服务端失败。 请检查： 1.本地网络是否通畅？ 2.服务端是否开启？", 3)
        // $router.push("/login")
    }
    //console.log("【error】", error)
    return Promise.reject(error)
});

function closeLoading() {
    useLayoutStore().windowLoading = false;
    useLayoutStore().pageLoading = false;
}

export default $http

